package com.iecm.listener;

import com.alibaba.fastjson.JSONObject;
import com.iecm.common.utils.RedisUtil;
import com.iecm.tcp.channel.TcpChannel;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class JobListener {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TcpChannel tcpChannel;

    @RabbitListener(queues = "job_queue")
    @RabbitHandler
    public void receiveJob(JSONObject object, Channel channel, Message message){
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            String messageId = message.getMessageProperties().getHeaders().get("spring_returned_message_correlation").toString();
            if(redisUtil.hasKey("message:"+messageId)){
                return;
            }
            redisUtil.set("message:"+messageId, messageId, 1000);
            if (redisUtil.hHasKey("sys-netty", object.getString("collectorId"))) {
                String channelId = redisUtil.hget("sys-netty", object.getString("collectorId")).toString();
                tcpChannel.writeToClient(channelId, object.getString("revertStr"), object.getString("mark"));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
